home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 7 / Apprentice-Release7.iso / Utilities / Programming / C Reference Card 3.0 / C Reference Card / C Reference Card.rsrc / TEXT_401_1.txt < prev    next >
Encoding:
Text File  |  1997-07-17  |  8.3 KB  |  209 lines

  1. BASICS : C versus C++, program form, data types, strings, constants ...
  2. _________________________________________________________________________
  3.  
  4.  
  5. C VERSUS C++
  6.  
  7. C is a subset of C++.  An ANSI C program file should compile on a C++ compiler with little or no changes.  If your wondering whether you should learn one or the other - don't.  Learn C++ and you'll get the benefits of both C and C++.
  8.  
  9. This reference documents a combination of ANSI C and C++.  C++ additions to ANSI C are identified throughout the reference.
  10.  
  11.  
  12.  
  13. PROGRAM FORM
  14.  
  15. As an ongoing tradition, the first program you write should be the infamous ANSI C "Hello World" program.
  16.  
  17.   // hello.c
  18.   #include <stdio.h>
  19.  
  20.   main()               // by default, main returns an int
  21.   {
  22.     printf("hello world\n");
  23.  
  24.     return 0;          // successful program termination
  25.   }
  26.   // end hello.c
  27.  
  28. Here's the equivalent "Hello World" program in C++ using streams:
  29.  
  30.   // hello.cp
  31.   #include <iostream.h>
  32.  
  33.   main()
  34.   {
  35.     cout << "hello world" << endl;
  36.     
  37.     return 0;
  38.   }
  39.   // end hello.cp
  40.  
  41. If a program is successful, it should return a zero.  Returning a value of '1' generally represents an unsuccessful program termination.  You can also use the EXIT_SUCCESS and/or EXIT_FAILURE definitions located in the standard library file (i.e., stdlib.h).
  42.  
  43. Anything on a line after a double slash (//) is ignored by the compiler and is the standard way of commenting code in C++.  Another way to comment your code is to use the C-style slash-asterisk method.  The following program "square.cp" is almost as simple as the 'hello world' program, except it demonstrates the basics of using functions as well as both styles of comments.
  44.  
  45.   // square.cp
  46.   /*
  47.      Sometimes it convenient to use the "old" C-style comments,
  48.      especially when you have more than one line of stuff to say.
  49.   */
  50.  
  51.   #include <iostream.h> // standard library.
  52.  
  53.   #define MAX 10        // preprocessor directive.
  54.  
  55.   int DoSquare(int);    // function prototypes required in C++.
  56.  
  57.   main()                // main is the start of all C programs.
  58.   {
  59.     int n;
  60.     for(n=1;n<MAX;n++)
  61.       cout << n << " squared = " << DoSquare(n) << endl;
  62.  
  63.     return 0;
  64.   }
  65.  
  66.   int DoSquare(int m)   // function definition.
  67.   {
  68.     m = m * m;
  69.     return m;           // return value.
  70.   }
  71.   // end square.cp
  72.  
  73. White space is ignored in C/C++.  Brackets {} are used to group (or enclose) multiple statements.  Function calls are depicted with parenthesis () at the end of a function name which enclose variables which are used during the function call.  Semicolons depict the end of a statement (i.e., you can place multiple statements on a single line separated by semicolons if you wanted).
  74.  
  75.  
  76.  
  77. DATA TYPES AND TYPE CONVERSION
  78.  
  79. The following program identifies the built-in data types supported by C and methods for converting between these data types.
  80.  
  81.   // types.cp
  82.   #include <iostream.h>
  83.  
  84.   main()
  85.   {
  86.     // declarations
  87.     char                c = 'A';  // 1-byte long by definition (in C++).
  88.     short int           si= 1;    // minimum range +/-32767.
  89.     short               s = 2;    // short same as short int.
  90.     int                 i = 3;    // minimum range +/-32767.
  91.     long int            li= 4;    // minimum range +/-2147483647.
  92.     long                l = 5;    // long same as long int.
  93.     float               f = 10.1; // min 6 digits (decimal) precision.
  94.     double              d = 11.2; // min 10 digits (decimal) precision.
  95.     long double         ld= 12.3;
  96.  
  97.     unsigned char       uc;       // unsigned integers can only store
  98.     unsigned short int  usi;      // positive numbers.
  99.     unsigned int        ui;
  100.     unsigned long int   uli;
  101.  
  102.     signed char         sc;       // signed integers can store positive
  103.     signed short int    ssi;      // or negative numbers.
  104.     signed int          si2;
  105.     signed long int     sli;
  106.  
  107.     // simple assignment
  108.     s = 3;
  109.     cout << s << endl;
  110.  
  111.     // automatic conversion
  112.     f = s * i / d;
  113.     cout << f << endl;
  114.  
  115.     // inline conversions
  116.     ld = (long double)i;
  117.     s = short(d);
  118.     cout << ld << endl << s << endl;
  119.  
  120.     return 0;
  121.   }
  122.   // end types.cp
  123.  
  124.  
  125.  
  126. STRINGS
  127.  
  128. Strings in C are "null terminated".  This means that the following declaration;
  129.  
  130.   char *str = "Test string";
  131.  
  132. allocates a block of memory 12 bytes long and returns a pointer 'str' to the first character in the string.  The first 11 bytes contain the characters "Test string", the 12th byte contains NULL (i.e., \0 or zero).  To declare an empty string, use the following:
  133.  
  134.   char *nullStr = "";
  135.  
  136. Since the MacOS is based on Pascal strings, it is important that the difference be discussed.  The same string in Pascal would also be 12 bytes long, however, the first character in the string is actually the integer '11' which defines how many characters are in the string.  Your compiler should provide functions such as CtoPstr() and PtoCstr() to convert between the two formats.  If you want to declare a Pascal-style string in C, use the following:
  137.  
  138.   char *Pstr = "\pThis is a Pascal string";
  139.  
  140.  
  141.  
  142. CONSTANTS
  143.  
  144.   // constant definition examples
  145.   #define INTEGER         123
  146.   #define LONG            123L
  147.   #define UNSIGNED_LONG   123UL
  148.   #define FLOAT           12.3F
  149.   #define CHAR_CONST      'A'
  150.   #define OCTAL           037           /* leading zero */
  151.   #define HEXADECIMAL     0X5
  152.   #define STRING          "characters"
  153.  
  154.   // escape sequences
  155.   #define ALERT           \a
  156.   #define BACKSPACE       \b
  157.   #define FORMFEED        \f
  158.   #define NEWLINE         \n
  159.   #define CARRIAGE_RETURN \r
  160.   #define HORIZ_TAB       \t
  161.   #define VERT_TAB        \v
  162.   #define BACKSLASH       \\
  163.   #define QUESTION_MARK   \?
  164.   #define SINGLE_QUOTE    \'
  165.   #define DOUBLE_QUOTE    \"
  166.   #define OCTAL_SEQ       \o13          /* vertical tab */
  167.   #define HEX_SEQ         \x7           /* alert */
  168.  
  169.   // enumeration constants
  170.   enum boolean { FALSE, TRUE };
  171.   enum identifiers { first = 1, second, third };
  172.  
  173. The first item in an enumeration statement has a value of 0, the next 1, the next 2, etc. unless specified values are provided.
  174.  
  175.  
  176.  
  177. TERMINOLOGY
  178.  
  179. There‚Äôs a lot of fancy terminology in C++ which tends to confuse the novice.  Here are some of the buzz words that are used in object-oriented programming and what they mean:
  180.  
  181. Instances - Variables of a pre-defined class type are called instances of that class, or objects.
  182.  
  183. Objects - Objects are variables which are instances of a class.  Here is a simple example:
  184.  
  185.   class Student          // define class Student
  186.   {
  187.     char *name;
  188.     char *address;
  189.     int  id;
  190.  
  191.     void input( void );  // class methods
  192.     void print( void );
  193.   }
  194.  
  195.   Student freshman;      // freshman is an object,
  196.                          // a class variable, and
  197.                          // an instance of the class Student. 
  198.  
  199. Methods - Methods are nothing more than member functions of a class.
  200.  
  201. Polymorphism - When the same function works on different types of objects, it‚Äôs called polymorphism.  For example, you OPEN a door, you OPEN a window, and you OPEN your eyes.  Polymorphism means ‚Äúmany different forms‚Äù.
  202.  
  203. Encapsulation - The combination of member data and member functions (or methods) into an object.  With C++, you assign an object data attributes and methods which operate on the data.  Generally speaking, all of the code for a particular class of objects is maintained in a separate source code file, or in other words, it‚Äôs encapsulated.
  204.  
  205. Inheritance - One of the coolest things about C++ is that you can create an object which inherits all of the capabilities of a parent object, and then make minor modifications to suit your needs.  For example, if there was a window class which did everything you needed except for, say, window resizing.  You could create a subclass of the window class and then add the code needed to perform the task.  There are two important things to realize: 1) you only need to add the code to perform the specific task you need, and; 2) you don‚Äôt need the original source code of the parent class to make modifications.
  206.  
  207. Multiple Inheritance - Inheriting capabilities or traits from more than one parent defines multiple inheritance.  There are some problems with using multiple inheritance and many programmers avoid it at all costs (similar to using goto statements), but there are times when it can be useful.
  208.  
  209. Virtual Function (or method) - Allows polymorphism by defining a function which is called by an object at runtime (i.e., late binding) instead of at compile time (i.e., early binding).